<template>
	<view>
		<view class="login-continer">
			<!-- 提示登录的图标 -->
			<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
			<!-- 登录按钮 -->
			<button type="primary" class="btn-login" @click="getUserInfo">一键登录</button>
			<!-- 登录提示 -->
			<view class="tips-text">
				不登录你玩个锤子
			</view>
		</view>
	</view>
</template>

<script>
	import {mapMutations,mapState} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {};
		},
		methods: {
			...mapMutations('m_user',['updateUserInfo','updateToken','updateRedirectInfo']),
			getUserInfo() {

				uni.getUserProfile({
					desc: '登录',
					lang: 'zh_CN',
					success: (res) =>{
						//把返回结果中中的userInfo赋值给组件数据userinfo
						this.updateUserInfo(res.userInfo)
						this.getToken(res)
					},
					fail:(err)=>{
						uni.$showMsg('取消了授权')
					}
				})

			},
			async getToken(info){
				const [err,res] = await uni.login().catch(err=>err)
				if(err||res.errMsg!=='login:ok') return uni.$showError('登录失败')
				
				const query = {
					code:res.code,
					encryptedData:info.encryptedData,
					iv:info.iv,
					rawData:info.rawData,
					signature:info.signature
				}
				// console.log(query)
				// 从服务器请求token
				// const {data:loginResult} = await uni.$http.post('/api/public/v1/users/wxlogin',query)
				// 别人搭的登陆接口关了,可以用fastmock搭的模拟登录功能
				uni.$http.baseUrl='https://www.fastmock.site/mock/1479b8ee7fbb761269662b23b8f933fa/ssy'
				const {data:loginResult} = await uni.$http.post('/login',query)
				if(loginResult.meta.status!==200) return uni.$showMsg('登录失败')
				uni.$showMsg('登录成功')
				this.updateToken(loginResult.message.token)
				this.navigateBack()
			},
			navigateBack(){
				if(this.redirectInfo&&this.redirectInfo.openType==='switchTab'){
					uni.switchTab({
						url:this.redirectInfo.from,
						complete:()=>{
							this.updateRedirectInfo(null)
						}
					})
				}
			}
		},
		computed:{
			...mapState('m_user',['redirectInfo'])
		}
	}
</script>

<style lang="scss">
	.login-continer {
		height: 750rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #F8F8F8;
		position: relative;
		overflow: hidden;

		.btn-login {
			width: 80%;
			border-radius: 15px;
			margin: 15px 0;
			background-color: #FF5A5F;
		}

		.tips-text {
			padding-top: 10px;
			font-size: 12px;
			color: gray;
		}
	}
</style>
